# -*- encoding: utf-8 -*-
#import odoo.addons.decimal_precision as dp
from odoo import models, fields, api, _
from odoo.addons import base_cw
from odoo.exceptions import UserError
from odoo.tools.float_utils import float_round, float_compare


class account_income_statement(models.Model):
    _name = 'account.income.statement'
    _description = u'利润表'
    _order = 'print_sequence'
    
    period_id = fields.Many2one('account.period', u'期别', ondelete="set null")
    sequence = fields.Integer(u'项次')
    name = fields.Char(u'项目')
    print_sequence = fields.Char(u'行次')
    balance = fields.Float(u'本月数', digits='Amount')
    year_balance = fields.Float(u'本年累计数', digits='Amount')
    tax_print_sequence = fields.Char(u'行次')
    tax_name = fields.Char(u'税别项目')
    tax_month = fields.Float(u'期末帐面数', digits='Amount')
    tax_year = fields.Float(u'年初帐面数', digits='Amount')
    master_id = fields.Many2one('account.report.format.designer', u'主档',ondelete="cascade")

    def init(self):
        self._cr.execute("""
                CREATE OR REPLACE FUNCTION account_income_statement_write(
                        period_t integer,
                        master_id_t integer,
                        tax_master_id_t integer,
                        uid_t integer)
                  RETURNS void AS
                $BODY$
                /*利润表

                -- DROP FUNCTION account_income_statement_write(integer,integer,integer)
                -- select account_income_statement_write(9,3,4,1)
                -- select *  from account_income_statement
                -- delete from account_income_statement

                */
                begin

                   delete from account_income_statement where master_id=master_id_t;
                   insert into account_income_statement(period_id,sequence,name,print_sequence,balance,year_balance,create_uid,create_date,master_id)
                   select period_t,a.sequence,a.name,a.print_sequence,a.a1,a.g1,uid_t,(now() at time zone 'UTC'),master_id_t
                      from  account_report_format_designer_line a left join account_report_format_designer b on a.master_id=b.id
                     where b.id=master_id_t
                       and report_type='income';
                    --a1当期(余额)   e1年初余额
                   update account_income_statement c set tax_month=a.a1,tax_year=a.e1,tax_name=a.name,tax_print_sequence=a.print_sequence
                    from  account_report_format_designer_line a left join account_report_format_designer b on a.master_id=b.id
                     where b.id=tax_master_id_t
                       and report_type='tax'
                       and c.sequence=a.sequence;
                end;
                $BODY$
                LANGUAGE plpgsql VOLATILE
                COST 100;
                   """)